﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace System {
    /// <summary>
    /// https://blog.csdn.net/farway000/article/details/118773404
    /// Ambiguous HTTP method for action OrderApi.Controllers.OrderController.Get (OrderApi). 
    /// Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0
    /// </summary>
    public class AutoHttpMethodOperationFitler:IDocumentFilter {
        private readonly string _defaultHttpMethod;
        /// <summary>
        /// https://blog.csdn.net/farway000/article/details/118773404
        /// Ambiguous HTTP method for action OrderApi.Controllers.OrderController.Get (OrderApi). 
        /// Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0
        /// </summary>
        /// <param name="defaultHttpMethod"></param>
        public AutoHttpMethodOperationFitler(string defaultHttpMethod = null) {
            _defaultHttpMethod=defaultHttpMethod;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="swaggerDoc"></param>
        /// <param name="context"></param>
        public void Apply(OpenApiDocument swaggerDoc,DocumentFilterContext context) {
            //通过DocumentFilterContext上下文可以获取到ApiDescription集合
            foreach(var apiDescription in context.ApiDescriptions) {
                //为null说明没有给Action添加HttpMethod
                if(string.IsNullOrEmpty(apiDescription.HttpMethod)) {
                    //这些逻辑是和AutoHttpMethodIfActionNoBind扩展方法保持一致的
                    var actionName = apiDescription.ActionDescriptor.RouteValues["action"];
                    string methodName = "POST";
                    if(actionName.StartsWith("get",StringComparison.OrdinalIgnoreCase)) {
                        methodName="GET";
                    } else if(actionName.StartsWith("put",StringComparison.OrdinalIgnoreCase)) {
                        methodName="PUT";
                    } else if(actionName.StartsWith("delete",StringComparison.OrdinalIgnoreCase)) {
                        methodName="DELETE";
                    }
                    apiDescription.HttpMethod=methodName;
                }
            }
        }
    }
}
